package jwt

import (
	"app/pkg/config"
	"fmt"
	"time"

	"github.com/dgrijalva/jwt-go"
)

//Jwtkey 秘钥 可通过配置文件配置
// var Jwtkey = []byte("blog_jwt_key")

type MyClaims struct {
	Uid int64 `json:"uid,omitempty"`
	jwt.StandardClaims
}

// CreateToken 生成token
func CreateToken(uid int64) (string, error) {
	nowTime := time.Now() //当前时间
	claims := MyClaims{
		Uid: uid,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: nowTime.AddDate(0, 0, config.Config.App.JwtSignTTL).Local().Unix(), //过期时间戳
			IssuedAt:  nowTime.Unix(),                                                     //当前时间戳
			Issuer:    config.Config.App.JwtIssuer,                                        //颁发者签名
			Subject:   "userToken",                                                        //签名主题
		},
	}
	tokenStruct := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return tokenStruct.SignedString([]byte(config.Config.App.JwtSignKey))
}

// CheckToken 验证token
func CheckToken(token string, sign string) (*MyClaims, bool) {
	tokenObj, err := jwt.ParseWithClaims(token, &MyClaims{}, func(token *jwt.Token) (interface{}, error) {
		return []byte(sign), nil
	})
	if err != nil {
		fmt.Printf("%+v", err)
		return nil, false
	}
	if key, _ := tokenObj.Claims.(*MyClaims); tokenObj.Valid {
		return key, true
	} else {
		return nil, false
	}
}
